package com.molyfun.parents.activity.common.attachment;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.common.ImageViewerActivity;
import com.molyfun.parents.activity.common.VideoPlayerActivity;
import com.molyfun.parents.rest.bean.MediaobjectlistBean;
import com.molyfun.parents.rest.bean.StringResponse;
import com.molyfun.parents.rest.bean.UploadUrlRequest;
import com.molyfun.parents.utils.UIUtils;
import com.molyfun.parents.utils.UrlUtils;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.molyfun.parents.utils.Const.VIDEO_COVER_SUFFIX;
import static com.molyfun.parents.utils.Const.VIDEO_COVER_SUFFIX_WITHOUT_HOTLINK;

/**
 * Created by william(liuchao.hit@gmail.com).
 * Date:10/25/16.
 * <p>
 * 添加资源需要Activity之间交互，无法接偶Activity，因此留有数据传入接口
 */
public class AttachmentView extends RecyclerView implements View.OnClickListener {

    private static final int COLUMN_COUNT = 4;

    private static final int MAX_ATTACHMENT_COUNT = 9;

    private List<MediaobjectlistBean> mAccachmentList;

    private Context context;
    LinearLayoutManager mLinearLayoutManager;
    private AttachmentAdapter mAttachmentAdapter;

    public AttachmentView(Context context, AttributeSet attrs, int defStyle) {
        this(context, attrs);
    }

    public AttachmentView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public AttachmentView(Context context) {
        super(context);
        init(context, null);
    }

    private void init(Context context, AttributeSet attrs) {
        this.context = context;
        mLinearLayoutManager = new LinearLayoutManager(context);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        setLayoutManager(mLinearLayoutManager);
//        layoutInflater = LayoutInflater.from(context);
//        layoutInflater.inflate(R.layout.widget_attachment, this);
        setHasFixedSize(true);

        mAccachmentList = new ArrayList<>(MAX_ATTACHMENT_COUNT);
        mAttachmentAdapter = new AttachmentAdapter();
        setAdapter(mAttachmentAdapter);
        mAttachmentAdapter.notifyDataSetChanged();
    }

    public void addList(List<MediaobjectlistBean> mediaAttachments) {
        if (mediaAttachments != null) {
            for (MediaobjectlistBean mediaAttachment : mediaAttachments) {
                mAccachmentList.add(mediaAttachment);
            }
            mAttachmentAdapter.notifyDataSetChanged();
        }
    }

    public void refreshList(List<MediaobjectlistBean> mediaAttachments) {
        if (mediaAttachments != null) {
            mAccachmentList = mediaAttachments;
            mAttachmentAdapter.notifyDataSetChanged();
        }
    }

    public void addAttachment(MediaobjectlistBean attachmentBean) {
        if (mAccachmentList.size() < MAX_ATTACHMENT_COUNT) {
            mAccachmentList.add(attachmentBean);
            mAttachmentAdapter.notifyDataSetChanged();
        }
    }

    public List<MediaobjectlistBean> getAttachment() {
        return mAccachmentList;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        }
    }


    public class AttachmentAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        public AttachmentAdapter() {
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new AttachmentViewHolder(LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.layout_attachment_cell, parent, false));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {

//            final TopicBean aidsEntity=mList.get(position);
            final AttachmentViewHolder attachmentViewHolder = (AttachmentViewHolder) holder;
            if (position == 0) {
                attachmentViewHolder.mDelImg.setVisibility(View.GONE);
                attachmentViewHolder.mAttachmentImg.setImageResource(R.mipmap.ic_attachment_add);
                attachmentViewHolder.mAttachmentImg.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mAccachmentList.size() >= MAX_ATTACHMENT_COUNT) {
                            UIUtils.showToast(getContext(), "最多只能9张图片");
                        }
                        if (mAttachmentAddCallback != null) {
                            mAttachmentAddCallback.onAttachmentAdd();
                        }
                    }
                });
            } else {
                final MediaobjectlistBean attachmentBean = mAccachmentList.get(position - 1);

                switch (attachmentBean.getType()) {
                    //图片
                    case 1:
                        attachmentViewHolder.mVideoPlay.setVisibility(View.GONE);
                        if (!TextUtils.isEmpty(attachmentBean.getUrl())) {

                            if (UrlUtils.isExpired(attachmentBean.getUrl())) {
                                UploadUrlRequest uploadUrlRequest = new UploadUrlRequest();
                                uploadUrlRequest.setUrl(UrlUtils.getNewUrl(attachmentBean.getUrl()));
                                Call<StringResponse> call = MFPApplication.getInstance().getRestClient().updateMediaUrl(uploadUrlRequest);
                                call.enqueue(new Callback<StringResponse>() {
                                    @Override
                                    public void onResponse(Call<StringResponse> call, Response<StringResponse> response) {
                                        attachmentBean.setUrl(response.body().getData());
                                        Picasso.with(getContext())
                                                .load(response.body().getData())
                                                .into(attachmentViewHolder.mAttachmentImg);
                                    }

                                    @Override
                                    public void onFailure(Call<StringResponse> call, Throwable t) {
                                    }
                                });
                            } else {
                                Picasso.with(getContext())
                                        .load(attachmentBean.getUrl())
                                        .placeholder(R.mipmap.ic_video_holder)
                                        .into(attachmentViewHolder.mAttachmentImg);
                            }

//                            Picasso.with(getContext())
//                                    .load(attachmentBean.getUrl())
//                                    .placeholder(R.mipmap.ic_video_holder)
//                                    .into(attachmentViewHolder.mAttachmentImg);
                        }
                        break;
                    //视频
                    case 2:
                        attachmentViewHolder.mVideoPlay.setVisibility(View.VISIBLE);

                        if (UrlUtils.isExpired(attachmentBean.getUrl())) {
                            UploadUrlRequest uploadUrlRequest = new UploadUrlRequest();
                            uploadUrlRequest.setUrl(UrlUtils.getNewUrl(attachmentBean.getUrl() + VIDEO_COVER_SUFFIX_WITHOUT_HOTLINK));
                            Call<StringResponse> call = MFPApplication.getInstance().getRestClient().updateMediaUrl(uploadUrlRequest);
                            call.enqueue(new Callback<StringResponse>() {
                                @Override
                                public void onResponse(Call<StringResponse> call, Response<StringResponse> response) {
                                    Picasso.with(getContext())
                                            .load(response.body().getData())
                                            .into(attachmentViewHolder.mAttachmentImg);
                                }

                                @Override
                                public void onFailure(Call<StringResponse> call, Throwable t) {
                                }
                            });
                        } else {
                            Picasso.with(getContext())
                                    .load(attachmentBean.getUrl() + VIDEO_COVER_SUFFIX)
                                    .into(attachmentViewHolder.mAttachmentImg);
                        }
//                            Picasso.with(getContext())
//                                    .load(attachmentBean.getUrl() + VIDEO_COVER_SUFFIX)
//                                    .into(attachmentViewHolder.mAttachmentImg);

                        break;
                }

                attachmentViewHolder.mDelImg.setVisibility(View.VISIBLE);
                attachmentViewHolder.mDelImg.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mAttachmentDelCallback != null) {
                            mAttachmentDelCallback.onAttachmentDel(mAccachmentList.get(position - 1));
                        }
                        mAccachmentList.remove(position - 1);
                        notifyDataSetChanged();
                    }
                });
                attachmentViewHolder.mAttachmentImg.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (attachmentBean.getType()) {
                            //图片
                            case 1:
                                //TODO 浏览大图
                                ImageViewerActivity.startActivity(context, attachmentBean.getUrl());
                                break;
                            //视频
                            case 2:
                                VideoPlayerActivity.startActivity(context, null, attachmentBean.getUrl());
                                break;
                        }
//                        //TODO 浏览大图
//                        ImageViewerActivity.startActivity(context, attachmentBean.getUrl());
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            if (mAccachmentList == null || mAccachmentList.size() == 0) {
                return 1;
            }
            return mAccachmentList.size() + 1;
        }

        public class AttachmentViewHolder extends RecyclerView.ViewHolder {

            @InjectView(R.id.attachment_img)
            CircleImageView mAttachmentImg;
            @InjectView(R.id.attachment_del)
            ImageView mDelImg;
            @InjectView(R.id.video_play_btn)
            ImageView mVideoPlay;

            public AttachmentViewHolder(View view) {
                super(view);
                ButterKnife.inject(this, view);
            }
        }
    }

    public void setAttachmentDelCallback(AttachmentDelCallback attachmentDelCallback) {
        this.mAttachmentDelCallback = attachmentDelCallback;
    }

    private AttachmentDelCallback mAttachmentDelCallback;

    public static interface AttachmentDelCallback {
        //call when picture add action
        public void onAttachmentDel(MediaobjectlistBean mediaobjectlistBean);
    }

    public void setAttachmentAddCallback(AttachmentAddCallback attachmentAddCallback) {
        this.mAttachmentAddCallback = attachmentAddCallback;
    }

    private AttachmentAddCallback mAttachmentAddCallback;

    public static interface AttachmentAddCallback {
        //call when picture add action
        public void onAttachmentAdd();
    }

}